package com.bupt.cad.service.impl;

import com.bupt.cad.entity.DataSource;
import com.bupt.cad.entity.DataSourceVo;
import com.bupt.cad.mapper.DataSourceDao;
import com.bupt.cad.service.IDataSourceService;
import com.bupt.cad.utils.CsvUtil;
import org.jumpmind.symmetric.csv.CsvReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

@Service
public class DataSourceService implements IDataSourceService {

    @Autowired
    DataSourceDao dataSourceDao;

/*
* rivate int id;
    private String name;
    private String type;
    private Map<String,Object> data;
    private int screenId;
    private String createTimestamp;
    private String updateTimestamp;
* */
    @Override
    public int insertDataSource(MultipartFile multipartFile, String name, int screenId) {
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if(suffix.equals(".csv")){
            DataSource dataSource = new DataSource();
            List<Map<String, Object>> maps = CsvUtil.Csv2Json(multipartFile);
            dataSource.setName(name);
            dataSource.setType("csv");
            dataSource.setData(maps);
            dataSource.setScreenId(screenId);
            if(dataSourceDao.insertDataSource(dataSource)!=0){
                return dataSource.getId();
            }else return 0;
        }
        else{
            return 0;
        }
    }

    @Override
    public DataSource getDataSource(int dataSourceId) {

        return dataSourceDao.getDataSourceById(dataSourceId);
    }

    @Override
    public List<DataSourceVo> getAllDataSource(int screenId) {

        return dataSourceDao.getAllDataSourceById(screenId);
    }
}
